import requests
from ..common.setting import API_URL
from ..common.config import cfg
def generate_coze_jwt() -> str | None:
    """ 通过 /coze-jwt 接口获取 encoded_jwt，再获取最终的 Coze API token """
    try:
        # 1. 从后端获取 encoded_jwt
        jwt_url = f"{API_URL}/coze-jwt"
        headers = {
            'Authorization': f'Bearer {cfg.get(cfg.jwtToken)}'
        }
        jwt_response = requests.get(jwt_url, headers=headers)
        jwt_response.raise_for_status()
        jwt_json = jwt_response.json()
        if jwt_json.get("status") != "success" or "coze_jwt" not in jwt_json:
            print(f"/coze-jwt 接口返回异常: {jwt_json}")
            return None
        encoded_jwt = jwt_json["coze_jwt"]

        # 2. 用 encoded_jwt 获取最终的 Coze API token
        token_url = 'https://api.coze.cn/api/permission/oauth2/token'
        token_headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {encoded_jwt}'
        }
        token_data = {
            "duration_seconds": 86399,
            "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"
        }
        response = requests.post(token_url, headers=token_headers, json=token_data)
        response.raise_for_status()
        final_token_data = response.json()
        return final_token_data.get("access_token")
    except requests.exceptions.RequestException as e:
        print(f"请求 Coze API token 时发生错误: {e}")
        return None
    except Exception as e:
        print(f"生成JWT时发生未知错误: {e}")
        return None